//
//  TransferViewController.m
//  EasyToTesco2.0
//
//  Created by knew on 2017/5/18.
//  Copyright © 2017年 EasyToTesco. All rights reserved.
//

#import "TransferViewController.h"
#import "DataMD5.h"
#import "ReadLoginData.h"
#import "RKAlertView.h"
#import "TransferRecodeTableViewController.h"
#import "ReadLogInData.h"


@interface TransferViewController ()<UITextFieldDelegate>

{
 
    NSString *_payType;
    NSString *_pwdStr;
    NSString *_memberNameString;
}

@property (nonatomic,strong)NSDictionary *dict;

@property (nonatomic,strong)UITextField *moneyTextField;

@property (nonatomic,strong)UIButton *transferBtn;

@property (nonatomic,strong)UIButton *cashBtn;

@property (nonatomic,strong)UIButton *standBtn;

@property (nonatomic, assign) BOOL isHaveDian;
@property (nonatomic, assign) BOOL isFirstZero;

@end

@implementation TransferViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@""] highImage:[UIImage imageNamed:@""] target:self action:@selector(selectTransferButtonClick) forControlEvents:UIControlEventTouchUpInside title:@"消费记录"];
    self.title = @"消费";
    _payType = @"3";
    [self showHudInView:self.view hint:@""];
    [self _loadUserInfoData];
    
    
    NSDictionary *params = @{
                             @"username":self.dict[@"username"]
                             };
    
    [[NetWorkSharedTools sharedNetWorkTools] GetObjectWithURLDict:params AndMenthodName:@"/api/Chat/memberInfo" completeBlock:^(id object) {
        //            NSLog(@"%@",object);
        if (JudgeBackDataCode) {
            NSDictionary *dict = [object objectForKey:@"data"];
            SellerUserInfoModel *infoModel = [[SellerUserInfoModel alloc] initWithDictionary:dict error:nil];
            _memberNameString = infoModel.member_image;
        } else {
            _memberNameString = @"";
        }
        [self _initWithUserInfo];
        
    }];
    
    self.view.backgroundColor = BACKGROUND_COLOR;
    
}


- (void)selectTransferButtonClick {
    TransferRecodeTableViewController *transfer = [[TransferRecodeTableViewController alloc] init];
    transfer.transferNum = @"18000000000";
    [self.navigationController pushForm:self.navigationController pushToAndHidden:transfer];
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
 
    [self.moneyTextField resignFirstResponder];
}


- (void)_loadUserInfoData {
    self.dict = [DataMD5 getURLParameters:self.urlString];
}

- (void)_initWithUserInfo {
    
    [self hideHud];
    
    UIImageView *image = [[UIImageView alloc] init];
    //    image.image = [UIImage imageNamed:@"icon"];
    NSLog(@"%@",_memberNameString);
    [image sd_setImageWithURL:[NSURL URLWithString:_memberNameString] placeholderImage:[UIImage imageNamed:@"icon"]];
    image.layer.cornerRadius = 15;
    image.layer.masksToBounds = YES;
    image.backgroundColor = [UIColor clearColor];
    [self.view addSubview:image];
    
    UILabel *nameLabel = [[UILabel alloc] init];
    nameLabel.text = self.dict[@"real_name"];
    nameLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:nameLabel];
    
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(self.view.mas_top).offset(124);
        make.width.mas_equalTo(WIDTH);
        make.height.mas_equalTo(25);
    }];
    
    [image mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.bottom.equalTo(nameLabel.mas_top).offset(-8);
        make.width.height.mas_equalTo(70);
    }] ;
    
    UILabel *numberLabel = [[UILabel alloc] init];
    numberLabel.text = self.dict[@"username"];
    numberLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:numberLabel];
    
    [numberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(nameLabel.mas_bottom);
        make.width.mas_equalTo(WIDTH);
        make.height.mas_equalTo(30);
    }];
    
    UIView *trans = [[UIView alloc] initWithFrame:CGRectMake(nameLabel.x, numberLabel.y + 8, WIDTH, 130)];
    trans.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:trans];
    
    [trans mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(numberLabel.mas_bottom).offset(8);
        make.centerX.equalTo(self.view.mas_centerX);
        make.width.mas_equalTo(WIDTH);
        make.height.mas_equalTo(130);
    }];
    
    UILabel *label = [[UILabel alloc] init];
    label.text = @" 消费金额";
    [trans addSubview:label];
    
    UIView *topLine = [[UIView alloc] init];
    topLine.backgroundColor = BACKGROUND_COLOR;
    [trans addSubview:topLine];
    
    [topLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(trans);
        make.height.mas_equalTo(1);
        make.width.mas_equalTo(WIDTH);
    }];
    
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(trans.mas_left).offset(4);
        make.top.equalTo(trans.mas_top);
        make.width.mas_equalTo(WIDTH * 0.3);
        make.height.mas_equalTo(30);
    }];
    
    UITextField *textField = [[UITextField alloc] init];
    textField.borderStyle = UITextBorderStyleNone;
    //    textField.placeholder = @"请输入转账金额";
    textField.font = [UIFont systemFontOfSize:40];
    textField.keyboardType = UIKeyboardTypeDecimalPad;
    [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.moneyTextField = textField;
    self.moneyTextField.delegate = self;
    [trans addSubview:textField];
    
    UIImage *im = [UIImage imageNamed:@"money"];
    UIImageView *iv = [[UIImageView alloc] initWithImage:im];
    iv.contentMode = UIViewContentModeScaleToFill;
    [trans addSubview:iv];
    
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(trans.mas_left).offset(28);
        make.top.equalTo(label.mas_bottom).offset(8);
        make.width.mas_equalTo(WIDTH);
        make.height.mas_equalTo(32);
    }];
    
    [iv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(textField.mas_left).offset(0);
        make.centerY.equalTo(textField.mas_centerY);
        make.width.height.mas_equalTo(24);
    }];
    
    UIView *bottomLine = [[UIView alloc] init];
    bottomLine.backgroundColor = BACKGROUND_COLOR;
    [trans addSubview:bottomLine];
    
    [bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(trans.mas_left);
        make.top.equalTo(textField.mas_bottom).offset(8);
        make.width.mas_equalTo(WIDTH);
        make.height.mas_equalTo(1);
    }];
    UIButton *standBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [standBtn setImage:[UIImage imageNamed:@"gouwuche_0"] forState:UIControlStateNormal];
    [standBtn setTitle:@"代金券" forState:UIControlStateNormal];
    [standBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [standBtn addTarget:self action:@selector(didClickChooseButton:) forControlEvents:UIControlEventTouchUpInside];
    standBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    standBtn.imageView.contentMode = UIViewContentModeScaleToFill;
    [standBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 10)];
    standBtn.tag = 10;
    self.standBtn = standBtn;
    [trans addSubview:standBtn];
    
    [standBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(trans.mas_left).offset(4);
        make.top.equalTo(bottomLine.mas_bottom);
        make.bottom.equalTo(trans.mas_bottom);
        make.width.mas_equalTo(WIDTH * 0.3);
    }];
    
    UIButton *cashBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cashBtn setImage:[UIImage imageNamed:@"gouwuche_2"] forState:UIControlStateNormal];
    [cashBtn setTitle:@"充值账户" forState:UIControlStateNormal];
    [cashBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [cashBtn addTarget:self action:@selector(didClickChooseButton:) forControlEvents:UIControlEventTouchUpInside];
    cashBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    cashBtn.imageView.contentMode = UIViewContentModeScaleToFill;
    [cashBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 10)];
    cashBtn.tag = 11;
    self.cashBtn = cashBtn;
    [trans addSubview:cashBtn];
    
    [cashBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(standBtn.mas_right);
        make.top.bottom.width.mas_equalTo(standBtn);
    }];
    
    UIButton *transferBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [transferBtn setTitle:@"确认消费" forState:UIControlStateNormal];
    [transferBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [transferBtn setBackgroundColor:[UIColor lightGrayColor]];
    transferBtn.layer.cornerRadius = 5;
    transferBtn.layer.masksToBounds = YES;
    transferBtn.enabled = NO;
    [transferBtn addTarget:self action:@selector(didClickTransferBtn) forControlEvents:UIControlEventTouchUpInside];
    self.transferBtn = transferBtn;
    [self.view addSubview:transferBtn];
    
    [transferBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(trans.mas_bottom).offset(16);
        make.width.mas_equalTo(WIDTH * 0.9);
        make.height.mas_equalTo(40);
    }];
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [cancelBtn setBackgroundColor:[UIColor lightGrayColor]];
    cancelBtn.layer.cornerRadius = 5;
    cancelBtn.layer.masksToBounds = YES;
    [cancelBtn addTarget:self action:@selector(didClickCancelBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cancelBtn];
    
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(transferBtn.mas_bottom).offset(16);
        make.width.height.mas_equalTo(transferBtn);
    }];
    
}

- (void)didClickChooseButton:(UIButton *)button {
    if (button.tag == 10) {
        [self.standBtn setImage:[UIImage imageNamed:@"gouwuche_0"] forState:UIControlStateNormal];
        [self.cashBtn setImage:[UIImage imageNamed:@"gouwuche_2"] forState:UIControlStateNormal];
        _payType = @"3";
    } else {
        _payType = @"2";
        [self.standBtn setImage:[UIImage imageNamed:@"gouwuche_2"] forState:UIControlStateNormal];
        [self.cashBtn setImage:[UIImage imageNamed:@"gouwuche_0"] forState:UIControlStateNormal];
    }
    
}

- (void)didClickCancelBtn {
    [self.moneyTextField resignFirstResponder];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)didClickTransferBtn {
    [self.moneyTextField resignFirstResponder];
    
    if ([_payType isEqualToString:@"2"] || [_payType isEqualToString:@"3"]) {
        [RKAlertView showAlertPlainTextWithTitle:@"请输入支付密码" message:nil cancelTitle:@"取消" confirmTitle:@"确认" alertViewStyle:UIAlertViewStylePlainTextInput confrimBlock:^(UIAlertView *alertView) {
            NSLog(@"确认了输入：%@",[alertView textFieldAtIndex:0].text);
            _pwdStr = [alertView textFieldAtIndex:0].text;
            NSLog(@"%@",_pwdStr);
            
            [self didClickTransferBtnDataSource];
            
        } cancelBlock:^{
            
        }];
    } else {
        
    }
}

- (void)didClickTransferBtnDataSource {
    
    NSDate *datenow = [NSDate date];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    
    NSString *eightString = [USERNAME substringFromIndex:3];
    
    NSString *stirng = [NSString stringWithFormat:@"%@%@%@%@%.2f%@%@",USERNAME,eightString,self.dict[@"username"],_payType,self.moneyTextField.text.floatValue,_pwdStr,timeSp];
    
    NSString *token = [[DataMD5 sharedDataMD5] md5:stirng];
    NSDictionary *dict = @{
                           @"token":token,
                           @"username":USERNAME,
                           @"seller_name":self.dict[@"username"],
                           //                           2现金   3积分
                           @"pay_type":_payType,
                           @"timestamp":timeSp,
                           @"money":[NSString stringWithFormat:@"%.2f",self.moneyTextField.text.floatValue],
                           @"password":_pwdStr
                           };
    
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:dict AndMenthodName:@"/api/User/merchantPay" completeBlock:^(id object) {
        if (JudgeBackDataCode) {
            [MBProgressHUD showMessage:@"消费成功" toView:self.view dimBackground:NO AndCompleteBlock:^(id object) {
                [self.navigationController popToRootViewControllerAnimated:YES];
            }];
        } else {
            [self showHint:[NSString stringWithFormat:@"%@",[object[@"message"] objectForKey:@"msg"]]];
        }
    }];
    
}

- (void)textFieldDidChange:(UITextField *)textField {
    
    if (textField.text.length > 0) {
        self.transferBtn.enabled = YES;
        [self.transferBtn setBackgroundColor:DEFAULT_COLOR];
    } else {
        self.transferBtn.enabled = NO;
        [self.transferBtn setBackgroundColor:[UIColor lightGrayColor]];
    }
    
    if (textField == self.moneyTextField) {
        if (iPhone5) {
            if (textField.text.length >= 12) {
                textField.text = [textField.text substringToIndex:11];
            }
            
            if (textField.text.length >11) {
                NSLog(@"%@",textField.text);
                //            self.nameNumberString = textField.text;
            } else {
                //            self.belongLabel.text = BelongLabelText;
            }
            
        } else {
            if (textField.text.length >=14) {
                textField.text = [textField.text substringToIndex:13];
            }
            if (textField.text.length >13) {
                NSLog(@"%@",textField.text);
                //            self.nameNumberString = textField.text;
            } else {
                //            self.belongLabel.text = BelongLabelText;
            }
        }
    }
}

#pragma mark- UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == self.moneyTextField) {
        
        if ([textField.text rangeOfString:@"."].location==NSNotFound) {
            _isHaveDian = NO;
        }
        if ([textField.text rangeOfString:@"0"].location==NSNotFound) {
            _isFirstZero = NO;
        }
        
        if ([string length]>0)
        {
            unichar single=[string characterAtIndex:0];//当前输入的字符
            if ((single >='0' && single<='9') || single=='.')//数据格式正确
            {
                
                if([textField.text length]==0){
                    if(single == '.'){
                        //首字母不能为小数点
                        return NO;
                    }
                    if (single == '0') {
                        _isFirstZero = YES;
                        return YES;
                    }
                }
                
                if (single=='.'){
                    if(!_isHaveDian)//text中还没有小数点
                    {
                        _isHaveDian=YES;
                        return YES;
                    }else{
                        return NO;
                    }
                }else if(single=='0'){
                    if ((_isFirstZero&&_isHaveDian)||(!_isFirstZero&&_isHaveDian)) {
                        //首位有0有.（0.01）或首位没0有.（10200.00）可输入两位数的0
                        if([textField.text isEqualToString:@"0.0"]){
                            return NO;
                        }
                        NSRange ran=[textField.text rangeOfString:@"."];
                        int tt=(int)(range.location-ran.location);
                        if (tt <= 2){
                            return YES;
                        }else{
                            return NO;
                        }
                    }else if (_isFirstZero&&!_isHaveDian){
                        //首位有0没.不能再输入0
                        return NO;
                    }else{
                        return YES;
                    }
                }else{
                    if (_isHaveDian){
                        //存在小数点，保留两位小数
                        NSRange ran=[textField.text rangeOfString:@"."];
                        int tt= (int)(range.location-ran.location);
                        if (tt <= 2){
                            return YES;
                        }else{
                            return NO;
                        }
                    }else if(_isFirstZero&&!_isHaveDian){
                        //首位有0没点
                        return NO;
                    }else{
                        return YES;
                    }
                }
            }else{
                //输入的数据格式不正确
                return NO;
            }
        }else{
            return YES;
        }
    }
    return YES;
}

- (NSDictionary *)dict {
    if (!_dict) {
        _dict = [NSDictionary dictionary];
    }
    return _dict;
}
@end
